<template>
  <div class="home">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <el-card class="welcome-card" shadow="hover">
        <div class="welcome-content">
          <h1>欢迎使用杜伊斯堡签证预约平台</h1>
          <p>快速、便捷的在线预约服务，让您的签证办理更加高效</p>
        </div>
      </el-card>
    </div>


    <!-- 申请表单 -->
    <div class="form-section">
      <el-card class="form-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><Edit /></el-icon>
            <span>预约申请</span>
          </div>
        </template>

        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          :label-width="isMobile ? '80px' : '120px'"
          label-position="left"
          :size="isMobile ? 'default' : 'large'"
        >
          <!-- 基本信息 -->
          <el-divider content-position="left">基本信息</el-divider>
          
          <el-row :gutter="isMobile ? 0 : 20">
            <el-col :span="isMobile ? 24 : 8">
              <el-form-item label="称呼" prop="anrede">
                <el-select v-model="form.anrede" placeholder="请选择称呼" style="width: 100%">
                  <el-option label="Herr" value="Herr" />
                  <el-option label="Frau" value="Frau" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="isMobile ? 24 : 8">
              <el-form-item label="名字" prop="first_name">
                <el-input v-model="form.first_name" placeholder="请输入名字" />
              </el-form-item>
            </el-col>
            <el-col :span="isMobile ? 24 : 8">
              <el-form-item label="姓氏" prop="last_name">
                <el-input v-model="form.last_name" placeholder="请输入姓氏" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="isMobile ? 0 : 20">
            <el-col :span="isMobile ? 24 : 12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱地址" />
              </el-form-item>
            </el-col>
            <el-col :span="isMobile ? 24 : 12">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  placeholder="请选择生日"
                  format="DD.MM.YYYY"
                  value-format="DD.MM.YYYY"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="isMobile ? 0 : 20">
            <el-col :span="24">
              <el-form-item label="申请服务" prop="service">
                <el-select v-model="form.service" placeholder="请选择服务类型" style="width: 100%">
                  <el-option
                    v-for="service in services"
                    :key="service.name"
                    :label="service.name"
                    :value="service.name"
                  >
                    <span style="float: left">{{ service.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ service.duration }}分钟
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 时间范围选择 -->
          <el-divider content-position="left">预约时间范围（可选）</el-divider>
          <el-row :gutter="isMobile ? 0 : 20">
            <el-col :span="24">
              <el-form-item label="期望时间">
                <el-date-picker
                  v-model="form.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="isMobile ? 0 : 20">
            <el-col :span="24">
              <el-alert
                title="时间范围说明"
                type="info"
                :closable="false"
                show-icon
              >
                <template #default>
                  <p>• 不选择时间范围：系统将自动扫描当月及下月前7天</p>
                  <p>• 选择时间范围：系统仅在此范围内查找可用时间</p>
                  <p>• 只有找到的时间在指定范围内才会触发预约</p>
                </template>
              </el-alert>
            </el-col>
          </el-row>

          <!-- 其他信息（可选） -->
          <el-divider content-position="left">其他信息（可选）</el-divider>
          
          <el-row :gutter="isMobile ? 0 : 20">
            <el-col :span="isMobile ? 24 : 8">
              <el-form-item label="电话">
                <el-input v-model="form.phone" placeholder="请输入电话号码" />
              </el-form-item>
            </el-col>
            <el-col :span="isMobile ? 24 : 8">
              <el-form-item label="地址">
                <el-input v-model="form.address" placeholder="请输入详细地址" />
              </el-form-item>
            </el-col>
            <el-col :span="isMobile ? 24 : 8">
              <el-form-item label="邮编">
                <el-input v-model="form.zip_code" placeholder="请输入邮编" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 提交按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              :size="isMobile ? 'default' : 'large'"
              :loading="submitting"
              @click="submitForm"
              :style="{ width: isMobile ? '100%' : '200px' }"
            >
              <el-icon><Check /></el-icon>
              提交申请
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 申请ID显示区域 -->
    <div v-if="showRequestId" class="request-id-section">
      <el-card class="request-id-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><DocumentCopy /></el-icon>
            <span>申请ID</span>
          </div>
        </template>
        
        <div class="request-id-content">
          <div class="request-id-display">
            <el-input
              :model-value="lastRequestId"
              readonly
              size="large"
              class="request-id-input"
            >
              <template #append>
                <el-button @click="copyRequestId" type="primary">
                  <el-icon><CopyDocument /></el-icon>
                  复制
                </el-button>
              </template>
            </el-input>
          </div>
          
          <div class="request-id-tips">
            <el-alert
              title="重要提示"
              type="info"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>请保存此申请ID，您可以使用它来查询申请状态。</p>
                <p>请检查您的邮箱并点击确认链接以完成申请。</p>
              </template>
            </el-alert>
          </div>
          
          <div class="request-id-actions">
            <el-button type="primary" @click="goToStatus">
              <el-icon><Search /></el-icon>
              查询申请状态
            </el-button>
            <el-button @click="showRequestId = false">
              关闭
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 服务说明 -->
    <div class="info-section">
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><InfoFilled /></el-icon>
            <span>服务说明</span>
          </div>
        </template>
        
        <el-row :gutter="isMobile ? 10 : 20">
          <el-col :span="isMobile ? 24 : 8" v-for="service in services" :key="service.name">
            <div class="service-item">
              <h4>{{ service.name }}</h4>
              <p>{{ service.description }}</p>
              <el-tag type="info" size="small">约{{ service.duration }}分钟</el-tag>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Check, InfoFilled, DocumentCopy, CopyDocument, Search } from '@element-plus/icons-vue'
import api from '../utils/api'
import { checkAdminAuth } from '../utils/auth'

export default {
  name: 'Home',
  components: {
    Edit,
    Check,
    InfoFilled,
    DocumentCopy,
    CopyDocument,
    Search
  },
  setup() {
    const formRef = ref()
    const submitting = ref(false)
    const services = ref([])
    const lastRequestId = ref('')
    const showRequestId = ref(false)
    
    // 移动端检测
    const isMobile = computed(() => {
      return window.innerWidth <= 768
    })

    // 管理员认证状态
    const isAdminAuthenticated = computed(() => {
      return checkAdminAuth()
    })

    const form = reactive({
      anrede: '',
      first_name: '',
      last_name: '',
      email: '',
      phone: '',
      birthday: '',
      service: '',
      address: '',
      zip_code: '',
      dateRange: null
    })

    const rules = {
      anrede: [
        { required: true, message: '请选择称呼', trigger: 'change' }
      ],
      first_name: [
        { required: true, message: '请输入名字', trigger: 'blur' }
      ],
      last_name: [
        { required: true, message: '请输入姓氏', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      birthday: [
        { required: true, message: '请选择生日', trigger: 'change' }
      ],
      service: [
        { required: true, message: '请选择服务类型', trigger: 'change' }
      ]
    }

    // 获取服务列表
    const loadServices = async () => {
      try {
        const response = await api.getServices()
        if (response.data.success) {
          services.value = response.data.data
        }
      } catch (error) {
        ElMessage.error('获取服务列表失败')
        console.error('Error loading services:', error)
      }
    }

    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        submitting.value = true

        // 处理时间范围数据
        const formData = { ...form }
        if (form.dateRange && form.dateRange.length === 2) {
          // 将日期范围转换为日期数组
          const startDate = new Date(form.dateRange[0])
          const endDate = new Date(form.dateRange[1])
          const dateArray = []
          
          for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
            dateArray.push(d.toISOString().split('T')[0])
          }
          
          formData.dateRange = dateArray
        } else {
          formData.dateRange = null
        }

        const response = await api.register(formData)
        
        if (response.data.success) {
          const requestId = response.data.request_id
          
          // 保存申请ID并显示
          lastRequestId.value = requestId
          showRequestId.value = true
          
          // 显示成功消息
          ElMessage.success('申请已提交成功！请查看下方的申请ID')
          
          // 重置表单
          formRef.value.resetFields()
        } else {
          ElMessage.error(response.data.error || '提交失败，请重试')
        }
      } catch (error) {
        if (error.response) {
          ElMessage.error(error.response.data.error || '提交失败，请重试')
        } else {
          ElMessage.error('网络错误，请检查网络连接')
        }
      } finally {
        submitting.value = false
      }
    }

    // 复制申请ID
    const copyRequestId = async () => {
      try {
        await navigator.clipboard.writeText(lastRequestId.value)
        ElMessage.success('申请ID已复制到剪贴板')
      } catch (error) {
        ElMessage.warning('无法自动复制，请手动复制申请ID')
      }
    }

    // 跳转到状态查询页面
    const goToStatus = () => {
      // 这里可以使用Vue Router跳转，或者直接设置URL
      window.location.href = '/status'
    }

    // 禁用过去的日期
    const disabledDate = (time) => {
      return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
    }

    onMounted(() => {
      loadServices()
    })

    return {
      formRef,
      form,
      rules,
      submitting,
      services,
      lastRequestId,
      showRequestId,
      isMobile,
      isAdminAuthenticated,
      submitForm,
      copyRequestId,
      goToStatus,
      disabledDate
    }
  }
}
</script>

<style scoped>
.home {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.welcome-section {
  margin-bottom: 30px;
}

.welcome-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
}


.welcome-content {
  text-align: center;
  padding: 40px 20px;
}

.welcome-content h1 {
  font-size: 2.5rem;
  margin-bottom: 15px;
  font-weight: 300;
}

.welcome-content p {
  font-size: 1.2rem;
  opacity: 0.9;
}

.form-section {
  margin-bottom: 30px;
}

.form-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.request-id-section {
  margin-bottom: 30px;
}

.request-id-card {
  background: linear-gradient(135deg, #e8f5e8 0%, #f0f8f0 100%);
  border: 2px solid #28a745;
  border-radius: 10px;
}

.request-id-content {
  padding: 20px 0;
}

.request-id-display {
  margin-bottom: 20px;
}

.request-id-input {
  font-family: 'Courier New', monospace;
  font-size: 16px;
}

.request-id-tips {
  margin-bottom: 20px;
}

.request-id-actions {
  text-align: center;
  display: flex;
  gap: 15px;
  justify-content: center;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.info-section {
  margin-bottom: 30px;
}

.info-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.service-item {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  background: #f8f9fa;
  margin-bottom: 15px;
}

.service-item h4 {
  color: #333;
  margin-bottom: 10px;
  font-size: 16px;
}

.service-item p {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .home {
    padding: 5px;
  }
  
  .welcome-content h1 {
    font-size: 1.5rem;
    line-height: 1.3;
  }
  
  .welcome-content p {
    font-size: 0.9rem;
    line-height: 1.4;
  }
  
  .form-card, .welcome-card, .info-card {
    margin-bottom: 15px;
  }
  
  .card-header {
    font-size: 16px;
  }
  
  
  .request-id-actions {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
  
  .request-id-actions .el-button {
    width: 100%;
    max-width: 200px;
  }
  
  .service-item {
    margin-bottom: 10px;
    padding: 15px;
  }
  
  .service-item h4 {
    font-size: 14px;
  }
  
  .service-item p {
    font-size: 12px;
  }
  
  .el-form-item__label {
    font-size: 14px;
  }
  
  .el-input__inner, .el-select .el-input__inner {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .home {
    padding: 3px;
  }
  
  .welcome-content h1 {
    font-size: 1.3rem;
  }
  
  .welcome-content p {
    font-size: 0.8rem;
  }
  
  .form-card, .welcome-card, .info-card {
    margin-bottom: 10px;
  }
  
  .card-header {
    font-size: 14px;
  }
  
  
  .service-item {
    padding: 10px;
  }
  
  .service-item h4 {
    font-size: 13px;
  }
  
  .service-item p {
    font-size: 11px;
  }
}
</style>


